<?php
class CmsPostTagModel extends Model
{
    protected $resourceId = 'AdminResource';
    protected static $instance;
    protected $idField = 'post_id';

    public static function GetInstance()
    {
        return self::$instance ? self::$instance : self::$instance = new CmsPostTagModel();
    }

    public function Add($id, $tags)
    {
        $tags = String::ToArray($tags);
        $tagModel = CmsTagModel::GetInstance();
        foreach ($tags as $tag)
        {
            $tag = strtolower($tag);
            if (!$tagModel->IsExisted($tag)) $tagModel->Add($tag);
            $item[$this->idField] = $id;
            $item['tag_id'] = $tag;
            $this->Insert($item);
        }
    }

    public function Remove($id, $tagId)
    {
        $cond = new SqlQuery("DELETE FROM {$this->tableName} WHERE {$this->idField} = @{$this->idField} AND tag_id = @tag_id");
        $cond->AddNumber($this->idField, $id);
        $cond->AddString('tag_id', $tagId);
        $this->connection->Execute($cond);
    }

    public function GetTags($id)
    {
        return $this->FindBy($this->idField, $id, 'tag_id');
    }
}
?>
